package com.forumdemo.forum.controller;

import com.forumdemo.forum.common.AppResult;
import com.forumdemo.forum.common.ResultCode;
import com.forumdemo.forum.config.AppConfig;
import com.forumdemo.forum.model.User;
import com.forumdemo.forum.services.IUserService;
import com.forumdemo.forum.utils.MD5Util;
import com.forumdemo.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-10-19
 * Time: 17:29
 */

@Api(tags = "用户接口") // 对 UserController 进行说明
@Slf4j
@RestController// 表示返回的的结果是数据
@RequestMapping("/user")// 定义一级映射路径
public class UserController {


    @Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 密码
     * @param passwordRepeat 重复密码
     * @return
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 注解校验方式 👆
        // 传统的校验方式 👇
//        if (!StringUtils.hasLength(username)
//        || !StringUtils.hasLength(nickname)
//        || !StringUtils.hasLength(password)
//        || !StringUtils.hasLength(passwordRepeat)) {
//            // 返回错误信息（controller 不抛异常）
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        // 校验密码与重复密码是否相同
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        // 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 处理密码
        // 1. 生成盐
        String salt = UUIDUtil.UUID_32();
        // 2. 生成密文
        String encryptPassword = MD5Util.md5Salt(password, salt);
        // 3、 设置密码和盐
        user.setSalt(salt);
        user.setPassword(encryptPassword);

        // 调用 Service 层
        userService.createNormalUser(user);

        // 返回成功
        return AppResult.success();
    }


    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password) {
        // 1. 调用 Service 中的登录方法，返回 User 对象
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }

        // 2. 如果登录成功把 User对象 设置到 Session 作用域
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 3. 返回结果
        return AppResult.success();
    }



    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult getInfo(HttpServletRequest request,
                             @ApiParam("用户Id") @RequestParam(value = "id", required = false) Long id) {
        User user = null;
        // 1. 如果 id 为 null， 从 session 中获取当前登陆的用户信息
        if (id == null) {
            HttpSession session = request.getSession(false);
            // 判断 session 和用户信息是否有效
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                // 用户没有登录
                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
            }
            // 从session 中获取当前登陆的用户信息
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        } else {
            // 2. 如果 id 不为 null， 从数据库中按 id 查询出用户信息
            user = userService.selectById(id);
        }
        // 判断用户对象是否为 null
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 返回正常结果
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        // 获得 session对象
        HttpSession session = request.getSession(false);
        // 判断 session 是否有效
        if (session != null) {
            log.info("退出成功");
            // 表示用户在登录状态，直接销毁 session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }


    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username", required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender", required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                                @ApiParam("电话号") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        if (!StringUtils.hasLength(username)
        && !StringUtils.hasLength(nickname)
        && !StringUtils.hasLength(email)
        && !StringUtils.hasLength(phoneNum)
        && !StringUtils.hasLength(remark)
        && gender == null) {
            return AppResult.failed("请输入要修改的内容");
        }
        User updateUser = new User();
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        userService.modifyInfo(updateUser);

        // 查询更新后的用户信息
        user = userService.selectById(user.getId());
        // 把最新的用户信息设置到 session
        session.setAttribute(AppConfig.USER_SESSION, user);

        return AppResult.success(user);
    }


    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {

        // 校验新密码和确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 获取当前登陆的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调用 Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }
}
